package mytest.utility;

/**
 * Created by thinkpad on 2016/7/2.
 */
public class Ip {
    static final boolean isCidrDuplicated(String cidr1, String cidr2) {
        Integer[] result1 =  cidr2IpAndMask(cidr1);
        Integer[] result2 =  cidr2IpAndMask(cidr2);
        int mask = getMin(result1[1], result2[1]);
        if(mask > 0) {
            return Integer.toBinaryString(result1[0]).substring(0,mask)
                    .equals(Integer.toBinaryString(result2[0]).substring(0,mask));
        } else {
            return false;
        }
    }

    static Integer[] cidr2IpAndMask(String cidr) {
        //Todo Cidr参数校验正则
        String[] parts = cidr.split("/");
        String ip = parts[0];
        Integer[] value = new Integer[2];
        value[0] = ip2Integer(ip);
        value[1] = Integer.parseInt(parts[1]);
        return value;
    }

    public static final Integer ip2Integer(final String ip) {
        final String[] ipNums = ip.split("\\.");
        return (Integer.parseInt(ipNums[0]) << 24)
                + (Integer.parseInt(ipNums[1]) << 16)
                + (Integer.parseInt(ipNums[2]) << 8)
                + (Integer.parseInt(ipNums[3]));
    }

    public static int getMin(int x, int y) {
        return  x < y ? x:y;
    }
}
